package com.gary.springboot.component;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *  自定义拦截器  需要实现 HandlerInterceptor接口
 * @author pengrui
 * @date 2020/11/19 - 10:07
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     *  请求前进行拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获得session对象
        HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("loginUser");
        //若session中的loginUser对象为空 则返回登录页面
        if (loginUser == null) {
            request.setAttribute("msg", "你没有权限，请先登录");
            request.getRequestDispatcher("index.html").forward(request, response);
            return false;
        }
        return true;
    }
}
